package com.example.controller;

import com.example.User;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.core.handle.ModelAndView;

import java.io.IOException;

/**
 * @author xurongbei
 */
@Controller
@Mapping(value = "/hello")
public class HelloController {

    @Inject("${classpath:user.yml}")
    private User user;


    @Mapping(value = "/hello", method = MethodType.GET)
    public String hello(){
        System.out.println("user:"+user);
        return "Hello word!";
    }

    /**
     * 返回任何结构体，默认会以JSON格式输出
     * @return
     */
    @Mapping(value = "/json",method = MethodType.GET)
    public User home(){

        return new User("d东方不败",299);
    }

    /**
     * 通过ModelAndView 输出后端模板
     * @return
     */
    @Mapping(value = "/view")
    public ModelAndView home2(){

        return new ModelAndView("view.html");
    }

    /**
     * 获取请求参数
     * @param ctx
     * @return
     */
    @Mapping(value = "/param")
    public String param(Context ctx){
        String name = ctx.param("name");
        int age = ctx.paramAsInt("age",0);
        System.out.println("name:"+name+",age:"+age);
        ctx.param("name","world");
        return "param";
    }

    @Mapping(value = "/param2")
    public String param2(@Param String name){
        System.out.println("name:"+name);
        return "param2";
    }

    @Mapping(value = "/path/{name}")
    public String pathParam(@Path String name){
        System.out.println("name:"+name);
        return "pathParam";
    }

    @Mapping(value = "/bodyParam")
    public String bodyParam(Context ctx) throws IOException {
        String body = ctx.body();
        System.out.println("body:"+body);
        return "bodyParam";
    }

    /**
     * 测试重定向
     * @param ctx
     */
    @Mapping(value = "/")
    public void home3(Context ctx){
        //通过302方式，通知客户端跳转到 “/index.html” （浏览器会发生2次请求，地址会变成/login）
        ctx.redirect("/index.html");
    }
}
